package com.example.commonlibrary.mvi

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import java.lang.reflect.ParameterizedType

@Suppress("UNCHECKED_CAST")
abstract class BaseFragment<B: ViewDataBinding,VM:BaseViewModel<*,*>>():Fragment() {
    private val types by lazy {
        (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments
    }
    val binding:B by lazy {
        val clazz = types[0] as Class<B>
        clazz.getMethod("inflate", LayoutInflater::class.java).invoke(null,layoutInflater) as B
    }
    val viewModel:VM by lazy {
        val clazz = types[1] as Class<VM>
        ViewModelProvider(this)[clazz]
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View?  = binding.root

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initData()
        initView()
    }

    abstract fun initView()

    abstract fun initData()
}